import 'dart:async';

import 'package:get/get.dart';
import 'package:orginone/dart/base/common/emitter.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/core/public/consts.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/dart/core/provider/index.dart';
import 'package:orginone/main.dart';

import '../../base/common/commands.dart';
import 'task.dart';

/// 任务集合名
const TaskCollName = 'work-task';

abstract class IWorkProvider with EmitterMixin {
  late String userId;

  /// 当前用户
  late DataProvider user;
  RxList<IWorkTask> todos = <IWorkTask>[].obs;

  // 所有
  // RxList<IWorkTask> tasks = <IWorkTask>[].obs;

  /// 任务更新
  void updateTask(XWorkTask task);

  /// 加载实例详情
  Future<XWorkInstance?> loadInstanceDetail(
    String id,
    String targetId,
    String belongId,
  );

  /// 加载待办任务
  Future<List<IWorkTask>> loadTodos({bool reload = false});

  /// 加载任务数量
  Future<int> loadTaskCount(TaskType type);

  /// 加载任务事项
  Future<List<IWorkTask>> loadContent(TaskType type, {bool reload = false});
}

class WorkProvider with EmitterMixin implements IWorkProvider {
  WorkProvider(this.user) {
    kernel.on('RecvTask', [
      (dynamic data) {
        var work = XWorkTask.fromJson(data);
        // LogUtil.d(
        //     'XWorkTask:${work.title}-${work.taskType}-${work.approveType}');
        if (_todoLoaded && work.approveType != '抄送') {
          updateTask(work);
        }
      }
    ]);
  }
  @override
  final DataProvider user;
  @override
  RxList<IWorkTask> todos = <IWorkTask>[].obs;
  // @override
  // RxList<IWorkTask> tasks = <IWorkTask>[].obs;

  @override
  String get userId => user.user?.id ?? "";
  bool _todoLoaded = false;
  bool finished = false;
  // @override
  /// 每页条数
  int pageSize = 20;
  @override
  void updateTask(XWorkTask task) {
    final index = todos.indexWhere((i) => i.metadata.id == task.id);

    if (index > -1) {
      if (task.status! < TaskStatus.approvalStart.status) {
        todos[index].updated(task);
      } else {
        todos.removeAt(index);
      }
      changeCallback();
    } else {
      if (task.status! < TaskStatus.approvalStart.status) {
        todos.insert(0, WorkTask(task, user));

        changeCallback();
      }
      // todos.refresh();
    }

    // if (task.status != TaskStatus.approvalStart.status) {
    //   if (index < 0) {
    //     todos.insert(0, WorkTask(task, user));
    //   } else {
    //     todos[index].updated(task);
    //   }
    // } else if (index > -1) {
    //   todos.removeAt(index);
    // }
    // settingCtrl.todosCount.value = todos.length;
    // notity.changCallback();
  }

  @override
  Future<List<IWorkTask>> loadContent(TaskType type,
      {bool reload = false}) async {
    // LogUtil.e("loadContent==================${type.label}");

    if (type.label == '待办') {
      return await loadTodos(reload: reload);
    }
    return await loadTasks(type, reload, 0);
  }

  @override
  Future<List<IWorkTask>> loadTodos({bool reload = false}) async {
    if (!_todoLoaded || reload) {
      final res = await kernel.queryApproveTask(IdModel('0'));
      if (res.success) {
        _todoLoaded = true;
        todos.clear();
        todos.addAll((res.data?.result ?? [])
            .map((task) => WorkTask(task, user))
            .toList());
        // todos.refresh();
        changeCallback();
      }
    }
    return todos;
  }

  Future<List<IWorkTask>> loadTasks(TaskType type, [bool reload = false, int take = 10]) async {
    List<IWorkTask> tasks = [];
    // if (reload) {
    //   tasks = [];
    // }
    // int skip = tasks.length;
    // if (!finished) {
      var result = await kernel.collectionLoad<List<XWorkTask>>(
        // '445635922516643840', // PC的id
        userId,
        userId,
        [],
        TaskCollName,
        /*(type.label == '草稿') ? {
          'userData': [],
          'options': {
            'match': {
              'createUser': userId,
              'status': {
                '_gte_': 100,
              },
              'nodeId': {
                '_exists_': false,
              },
            },
            'sort': {
              'createTime': -1,
            },
            'project': {
              'data': 0
            }
          },
          'skip': 0,
          'take': 1000,
        } : */{
          'options': {
            'match': _typeMatch(type),
            'sort': {
              'createTime': -1,
            },
          },
          'skip': 0,
          'take': 1000, //pageSize,
        },
        fromJson: (data) {
          return XWorkTask.fromList(data['data'] is List ? data['data'] : []);
        },
      );
      // List<IWorkTask> taskDatas = [];
      if (result.success && result.data != null && result.data!.isNotEmpty) {
        result.data?.forEach((item) {
          if (tasks.every((i) => i.id != item.id)) {
            tasks.add(WorkTask(item, user));
          }
        });
      }
      tasks.where((i) => i.isTaskType(type)).toList();
      tasks.sort((a, b) {
      return DateTime.parse(b.metadata.updateTime ?? "")
          .compareTo(DateTime.parse(a.metadata.updateTime ?? ""));
      });
      // finished = taskDatas.length < 10;
      // tasks.addAll(taskDatas);
    // }
    return tasks;
  }

  @override
  Future<int> loadTaskCount(TaskType type) async {
    var res = await kernel.collectionLoad(
        userId,
        userId,
        [],
        TaskCollName,
        {
          "options": {
            "match": _typeMatch(type),
          },
          "isCountQuery": true,
        });
    if (res.success) {
      return res.data['totalCount'];
    }
    return 0;
  }

  @override
  Future<XWorkInstance?> loadInstanceDetail(
      String id, String targetId, String belongId) async {
    return await kernel.findInstance(targetId, belongId, id);
  }

  _typeMatch(TaskType type) {
    switch (type.label) {
      case '已办':
        return {
          'status': {
            '_gte_': 100,
          },
          'records': {
            '_exists_': true,
          },
        };
      case '已发起':
        return {
          'createUser': userId,
          'status': {
            // '_gte_': 100,
            '_lt_': 100,
          },
          'nodeId': {
            '_exists_': false,
          },
        };

      case '已完结':
        return {
          'createUser': userId,
          'status': {
            '_gte_': 100,
          },
          'nodeId': {
            '_exists_': false,
          },
        };
      case '抄送':
        return {
          'approveType': '抄送',
        };
      case '草稿':
        return {
          'userData': [],
          'options': {
            'match': {
              'createUser': userId,
              'status': {
                '_gte_': 100,
              },
              'nodeId': {
                '_exists_': false,
              },
            },
            'sort': {
              'createTime': -1,
            },
            'project': {
              'data': 0
            }
          },
          'skip': 0,
          'take': 30,
        };
      default:
        return {
          'status': {
            '_lt_': 100,
          },
        };
    }
  }

  @override
  dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
